<template>
  <div
    :title="view === 'create'? '新增': '编辑'"
    :visible="true"
    custom-class="dialogWrapper"
    :before-close="closeDialog"
    >
    <el-button type="primary" @click="closeDialog" class="retu">返回</el-button>
    <el-form :model="formData" label-width="80px" ref="ruleForm" :rules="rules">
    	<el-form-item label="归属栏目" required>
        <el-tree :data="tree" 
         show-checkbox
         node-key="id"
         @check-change="handleCheckChange"
         ref="tree">
        </el-tree>
      </el-form-item>
      <el-form-item label="Banner图文集合" prop="txt">
         <el-button type="primary" @click="condialogVisible = true">添加Banner图文集合</el-button>
      </el-form-item>
      <el-form-item label="">
                 <el-table
                  :data="formData.contentPictureBannerList"
                  style="width: 100%">
                  <el-table-column
                    prop="priority"
                    label="排序"
                    width="100px"
                   >
                  </el-table-column>
                  <el-table-column
                    label="图片"
                   >
                    <template scope="scope">
                      <img class="logoImg" :src="imgSrc(scope.row.imgPath)"/>
                    </template>
                  </el-table-column>
                   <el-table-column
                    prop="description"
                    label="图片介绍"
                    >
                  </el-table-column>
                  <el-table-column
                    prop="linkUrl"
                    label="链接地址">
                  </el-table-column>
                  <el-table-column label="操作" >
                      <template scope="scope">
                     <el-button
                        size="small"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row, formData.contentPictureBannerList)">删除</el-button>
                      </template>
                   </el-table-column>
                </el-table>
      </el-form-item>
      <el-form-item label="内容标题" prop="title" required>
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <div class="titleImg">
      <el-form-item label="标题图片路径" prop="titleImg">
      	<div class="editImg" v-if="imgShow === 'edit'">
      		<img :src="imgSrc(formData.titleImg)" />
      	</div>
        <el-upload
				  :action="baseUrl()"
				  class="upload-demo"
          :data="dataObj"
				  list-type="picture-card"
				  accept="image/jpeg,image/gif,image/png,image/bmp"
				  :on-preview="handlePictureCardPreview"
				  :on-remove="handleRemove"
				  :on-change="handleChangeImg"
          :on-success="titleImgSuccess"
				  :auto-upload = "true"
          :on-error="handleError"
				  :drag="false"
				  >
				  <i class="el-icon-plus"></i>
				   <div slot="tip" class="el-upload__tip">建议尺寸：450*380</div>
				</el-upload>
				<el-dialog :visible.sync="dialogVisible" size="tiny">
				  <img width="100%" :src="dialogImageUrl" alt="">
				</el-dialog>
      </el-form-item>
      </div>
      <div class="contentImg">
      <el-form-item label="内容图片路径" prop="contentImg">
      	<div class="editImg" v-if="imgShows === 'edit'">
      		<img :src="imgSrc(formData.contentImg)" />
      	</div>
        <el-upload
				  :action="baseUrl()"
				  class="upload-demo"
				  list-type="picture-card"
          :data="dataObj"
				  accept="image/jpeg,image/gif,image/png,image/bmp"
				  :on-preview="handlePictureCardPreview"
				  :on-remove="handleRemove"
				  :on-change="handleChangeImg2"
          :on-success="contentImgSuccess"
				  :auto-upload = "true"
          :on-error="handleError"
				  :drag="false"
				  >
				  <i class="el-icon-plus"></i>
				   <div slot="tip" class="el-upload__tip">建议尺寸：450*380</div>
				</el-upload>
				<el-dialog :visible.sync="dialogVisible" size="tiny">
				  <img width="100%" :src="dialogImageUrl" alt="">
				</el-dialog>
      </el-form-item>
      </div>
       <el-form-item label="富文本编辑器" prop="txt">
         <tinymce  v-model.trim="formData.txt"></tinymce>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submit('ruleForm')">确 定</el-button>
    </div>
    <!-- addContent -->
    <el-dialog
        title="添加图文集合"
        :visible.sync="condialogVisible"
        width="30%"
        :before-close="handleClose"
        >
        <el-form :model="conformData" label-width="80px" ref="conruleForm" :rules="conRules">
          <el-form-item label="序号" required>
             <input v-model.trim="conformData.priority" class="inp"/>
          </el-form-item>
          <el-form-item label="介绍" >
             <input v-model.trim="conformData.description" class="inp"/>
          </el-form-item>
          <el-form-item label="图片" class="banner">
                  <el-upload
                    :action="baseUrl()"
                    class="upload-demo"
                    :data="dataObj"
                    list-type="picture-card"
                    accept="image/jpeg,image/gif,image/png,image/bmp"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-change="bannerhandleChangeImg"
                    :on-success="bannerImgSuccess"
                    :auto-upload = "true"
                    :on-error="handleError"
                    :drag="false"
                    >
                    <i class="el-icon-plus"></i>
                    <div slot="tip" class="el-upload__tip">建议尺寸：1040*280</div>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible" size="tiny">
                    <!-- <img width="100%" :src="dialogImageUrl" alt=""> -->
                  </el-dialog>
          </el-form-item>
          <el-form-item label="链接" >
             <input v-model.trim="conformData.linkUrl" class="inp"/>
          </el-form-item>
        </el-form>
         <span slot="footer" class="dialog-footer">
            <el-button @click="condialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="conSubmit('conruleForm')">确 定</el-button>
          </span>
    </el-dialog>
  </div>

</template>

<script>
import {queryMenuColumn} from '@/services/program'
import UE from '../../layout/ue'
import { create, edit } from "@/services/content";
import { RequestError } from "@/services/errors";
import { mapActions } from "vuex";
import Tinymce from "@/components/Tinymce";
import { imgSrcUrl } from "@/services/imgSrcUrl";
import AuthStorage from '@/services/storage.js'
import {deepClone} from '@/utilities/object'
export default {
  name: "edit-role",
  components: {UE,Tinymce},
  data () {
    return {
      conformData:{},
      condialogVisible: false,
      selectedOptions: [],
      dataObj: { token: AuthStorage.token, key: '' },
      tree:[],
      menus: [],
      list: [],
      parentdata:[],
      formData: {
        title: "",
        author: "",
        titleColor: "",
        isBold: "",
        titleImg: "",
        contentImg: "",
        txt:"",
        contentPictureBannerList:[
      
        ],
        contentPictureList:[
        ],
        columnList:[
        ]
      },
      dialogImageUrl: '',
      dialogVisible: false,
      dialogFormVisible: false,
      dialogFormVisible: false,
      menuInfo: [],
      imgShow:"",
      imgShows:"",
      dialogFormVisible: false,
      rules: {
           title: [{ required: true, message: "请填写内容标题", trigger: "blur" }]
      },
      conRules: {
            priority: [{ required: true, message: "请填写序号", trigger: "blur" }]
      }
    }
  },

  props: {
    view: {
      type: String,
      default: "create"
    }
  },
  methods: {
     handleClose(done) {
        this.condialogVisible = false;
      },
    handleChange(value) {
        console.log(value);
    },
    handleCheckChange(data, checked, indeterminate) {
        let myarr =this.$refs.tree.getCheckedNodes()
        this.formData.columnList = myarr;
    },
    async queryMenu(){
            let data = await queryMenuColumn();
            await this.$nextTick();
            this.tree = data.rootTrees;
    },
    imgSrc(data){
      	return imgSrcUrl() + data;
      },
    set(keys){
      this.$refs.tree.setCheckedKeys(keys,true)
    },
    closeDialog() {
      this.$emit("close");  
    },
    baseUrl(){
      return "/ecshop/console/upload/uploadImg.do";
    },
    handleRemove(file, fileList) {
    	
    },
    handleChangeImg(file,fileList){
    	this.imgShow = ""
    	  if(fileList.length > 1){
	    		this.$message.warning('当前限制选择 1个文件,多张图片覆盖第一张');
          fileList.shift()
        }
    	  var isJPG = ""
    	  if(file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'){
    		  isJPG = true
    	  }else{
    		  isJPG = false
    	  }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    handleChangeImg2(file,fileList){
    	this.imgShows = ""
    	  if(fileList.length > 1){
	    		this.$message.warning('当前限制选择 1个文件,多张图片覆盖第一张');
          fileList.shift()
        }
    	  var isJPG = ""
    	  if(file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'){
    		  isJPG = true
    	  }else{
    		  isJPG = false
    	  }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    bannerhandleChangeImg(file,fileList){
    	this.imgShows = ""
    	  if(fileList.length > 1){
	    		this.$message.warning('当前限制选择 1个文件,多张图片覆盖第一张');
          fileList.shift()
        }
    	  var isJPG = ""
    	  if(file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'){
    		  isJPG = true
    	  }else{
    		  isJPG = false
    	  }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    handleError(err, file, fileList){
        this.$message.error(err);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    titleImgSuccess(response, file, fileList){
      if(response.rspCode != "0000"){
          this.$message.error("图片上传失败!");
           
      }else{
        this.formData.titleImg = response.data;
      }
    },
    contentImgSuccess(response, file, fileList){
      if(response.rspCode != "0000"){
          this.$message.error("图片上传失败!");
         
      }else{
         this.formData.contentImg = response.data;
      }
    },
    bannerImgSuccess(response, file, fileList){
      if(response.rspCode != "0000"){
          this.$message.error("图片上传失败!");
         
      }else{
         this.conformData.imgPath = response.data;
         console.log(this.conformData)
      }
    },
    submit(formName) {
      if(this.formData.columnList.length<1){
        this.$message({
          message: '所属栏目不能为空',
          type: 'warning'
        });
        return;
      }
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            if (this.view === "create") {
              await create(this.formData);
            } else {
              await edit(this.formData);
            }
            this.dialogFormVisible = false;
            this.$emit("close", true);
            this.$message({
              showClose: true,
              message: "提交成功",
              type: "success"
            });
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        } else {
          return;
        }
      });
    },
     conSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
           this.condialogVisible = false;
           var copeobj = deepClone(this.conformData)
           this.formData.contentPictureBannerList.push(copeobj)
           console.log(this.formData)
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        } else {
          return;
        }
      });
    },
      handleDelete (index,rows,data,) {
        console.log(index,rows,data,)
        data.splice(index, 1);
      },
  },
  mounted() {},
  created(){
    this.queryMenu();
    this.formData.author = sessionStorage.getItem('user')
  }
};
</script>
<style>
.dialogWrapper {
  width: 640px;
}
.el-select {
  width: 100%;
}
.ue{
  z-index: 99999;
}
.el-dialog{
   z-index: 99;
}
.editImg{
	  overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    float: left;
}
.editImg img{
	width: 100%;
	height: 100%;
}
.retu{
  margin-bottom: 20px;
}
.inp{
  border: 1px solid gray;
  width: 300px;
  border-radius: 5px;
  height: 36px;
}
.banner .el-upload-list--picture-card .el-upload-list__item{
  width:100%;
}
</style>


